/* eslint-disable */
/**
 * 记忆函数：缓存函数的运算结果
 * @description
 */
export const cached = (fn) => {
    const cache = Object.create(null);
    return (str) => {
        const hit = cache[str];
        return hit || (cache[str] = fn(str));
  };
};
/**
 * 日期格式化
 * @param [formater] [t] 格式化规范 参数
 * @description
 * dateFormater('YYYY-MM-DD HH:mm', t) ==> 2019-06-26 18:30
 * dateFormater('YYYYMMDDHHmm', t) ==> 201906261830
 */
export const dateFormater = (formater, t) => {
    const date = t ? new Date(t) : new Date();
    const Y = `${date.getFullYear()}`;
    const M = date.getMonth() + 1;
    const D = date.getDate();
    const H = date.getHours();
    const m = date.getMinutes();
    const s = date.getSeconds();
    return formater.replace(/YYYY|yyyy/g, Y)
        .replace(/YY|yy/g, Y.substr(2, 2))
        .replace(/MM/g, (M < 10 ? '0' : '') + M)
        .replace(/DD/g, (D < 10 ? '0' : '') + D)
        .replace(/HH|hh/g, (H < 10 ? '0' : '') + H)
        .replace(/mm/g, (m < 10 ? '0' : '') + m)
        .replace(/ss/g, (s < 10 ? '0' : '') + s);
};
/**
 * base64数据导出文件，文件下载
 * @param [filename] [data] 保存文件名 保存数据
 * @description
 */
export const downloadFile = (filename, data) => {
    const DownloadLink = document.createElement('a');
    if (DownloadLink) {
        document.body.appendChild(DownloadLink);
        DownloadLink.style = 'display: none';
        DownloadLink.download = filename;
        DownloadLink.href = data;
      if (document.createEvent) {
          const DownloadEvt = document.createEvent('MouseEvents');
          DownloadEvt.initEvent('click', true, false);
          DownloadLink.dispatchEvent(DownloadEvt);
      } else if (document.createEventObject) DownloadLink.fireEvent('onclick');
      else if (typeof DownloadLink.onclick === 'function') DownloadLink.onclick();
      document.body.removeChild(DownloadLink);
  }
};
/**
 * 返回一个lower - upper之间的随机数
 * @param [lower] [upper] 最小值 最大值
 * @description lower、upper无论正负与大小，但必须是非NaN的数据
 */
export const random = (lower, upper) => {
    lower = +lower || 0;
    upper = +upper || 0;
    return Math.random() * (upper - lower) + lower;
};
/**
 * 防抖函数
 * @param
 * @description
 */
export const debounce = (fn, delay=500) => {
    let last = 0;
    let timeout = null; // 创建一个标记用来存放定时器的返回值
    return function(){
        let that = this;
        let args = arguments;
        let now = + new Date();
        if(now - last < delay){
            // 高频触发,更新到最新事件
            clearTimeout(timeout);
            timeout = setTimeout(function(){
                last = now;
                fn.apply(that, args)
            }, delay);
        } else {
            // 低频触发,缓存上次事件
            last = now;
            fn.apply(that, args);
        }
    }
};
/**
 * json 取值
 * @param [data] [path] 对象，取值路径
 * @description const a = {b:{c:{d:[{e:1},{f:2}]}}}
 *              const r = GET(a, 'b.c.d.0.e')
 *              const r = GET(a, ['b','c','d','0','e'])
 */
export const GET = (data, path, defaultValue = null) => {
    let currentData = data;
    const arrayPath = Array.isArray(path) ? path : path.split('.');
    for (let item of arrayPath) {
        currentData = currentData[item];
    }
    return currentData ? currentData : defaultValue;
};
/**
 * 单位换算
 * @param [num] [fixed] 数值，末位取值
 * @description conversion('4343')  =>> 肆千叁百肆拾叁元整
 */
export const unitConvert = (num, fixed = 1) => {
    if(!num) return;
    const moneyUnits = ['', '万', '亿', '万亿'];
        const dividend = 10000;
        let curentNum = Number(num);
        //转换数字
        let curentUnit = moneyUnits[0];
        //转换单位
        for (let i = 0; i < 4; i++) {
            curentUnit = moneyUnits[i];
            if (strNumSize(curentNum) < 5) {
                break;
            };
            curentNum = curentNum / dividend;
      };
      const m = curentNum.toFixed(fixed) + curentUnit;
      return m;
}
const strNumSize = (tempNum) => {
    const stringNum = typeof tempNum === 'string' ? tempNum : tempNum.toString();
    const index = stringNum.indexOf('.');
    let newNum = stringNum;
    if (index != -1) {
        newNum = stringNum.substring(0, index)
    };
    return newNum.length;
}
/**
 * 货币单位添加隔断
 * @param [strs] 保留两位小数的参数
 * @description formatCash(12121212) => 12,121,212
 */
export const formatCash = (strs) => {
    const str = typeof strs === 'string' ? strs : strs.toString()
    return str.split('').reverse().reduce((prev, next, index) => {
        return ((index % 3) ? next : (next + ',')) + prev
    })
}
/**
 * 货币单位换算
 * @param [n] 保留两位小数的参数
 * @description  conversion('234.34') => 贰百叁拾肆元叁角肆分
 */
export const conversion = (n) => {
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) return '零';
    let unit = '千百拾亿千百拾万千百拾元角分'
    let str = '';
    let un = '零壹贰叁肆伍陆柒捌玖';
    n += '00';
    let p = n.indexOf('.');
    if (p > 0) n = n.substring(0, p) + n.substr(p + 1, 2);
    unit = unit.substr(unit.length - n.length);
    for (let i = 0; i < n.length; i++){
      str += un.charAt(n.charAt(i)) + unit.charAt(i);
    }
    const m = str
            .replace(/零(千|百|拾|角)/g, "零")
            .replace(/(零)+/g, "零")
            .replace(/零(万|亿|元)/g, "$1")
            .replace(/(亿)万|壹(拾)/g, "$1$2")
            .replace(/^元零?|零分/g, "")
            .replace(/元$/g, "元整");
    return m;
}
/**
 * 时间倒计时
 * @param [UseTime] 时间以分钟为单位,120分钟<=>02:00:00<=>7200秒
 * @description 
 *  const timeCountDown = new TimeCountDown(65, res => {
        console.log(parseInt(res.time))
        console.log('time=>>>', `${res.hours}小时${res.minute}分钟${res.second}秒`)
    })
    setTimeout(() => {
        clearInterval(timeCountDown.timeout)
    }, 5000);
 */
export function TimeCountDown (UseTime, calkback, isInterval=true) {
    this.timeout = null
    let time = 60*60*(UseTime/60)
    const h = UseTime/60
    if(isInterval){
        this.timeout = setInterval(()=>{
            time -= 1;
            let hours  = parseInt(time / 60 / 60 % h , 10);
            let minute = parseInt(time / 60 % 60, 10);
            let second = parseInt(time % 60, 10);
            if(hours === 0 && minute === 0 && second === 0){
                clearInterval(this.timeout);
            }
            hours = hours < 10 ? `0${hours}` : hours;
            minute = minute < 10 ? `0${minute}` : minute;
            second = second < 10 ? `0${second}` : second;
            const obj = {
                time, // 折算成秒
                hours,
                minute,
                second,
            }
            calkback(obj)
        },1000)
    } else {
        time--;
        let hours  = parseInt(time / 60 / 60 % h , 10);
        let minute = parseInt(time / 60 % 60, 10);
        let second = parseInt(time % 60, 10);
        hours = hours < 10 ? `0${hours}` : hours;
        minute = minute < 10 ? `0${minute}` : minute;
        second = second < 10 ? `0${second}` : second;
        const obj = {
            time,
            hours,
            minute,
            second,
        }
        calkback(obj)
    }
}